package model.room;

import javax.swing.table.AbstractTableModel;
import java.util.List;

/**
 * @author mxd
 * @date 2024/5/26 0026
 */
/*
 * JTable 数据模型的通用类，要显示一个类的列表，只需新建一个类，继承这个抽象类，然后初始化datas 和 columnNames，
 * 然后重写 getProperty 方法即可
 */

public abstract class MyAbstractTableModel<T> extends AbstractTableModel {
    private static final long serialVersionUID = 1L;

    protected List<T> datas ;  //从数据库中查询出来的数据列表

    protected String[] columnNames; //要显示的表头



    protected abstract Object getProperty(Object obj, int columnIndex);

    @Override
    public int getColumnCount() {
        // TODO Auto-generated method stub
        return columnNames.length;
    }

    @SuppressWarnings("unchecked")
    public void setData(List<T> datas) {
        this.datas = datas;
    }

    public List<T> list() {
        return datas;
    }

    public Object getObject(int rowIndex) {
        return datas.get(rowIndex);
    }

    @Override
    public int getRowCount() {
        // TODO Auto-generated method stub
        return datas.size();
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public String getColumnName(int columnIndex) {
        // TODO Auto-generated method stub
        return columnNames[columnIndex] ;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        if (rowIndex > getRowCount() || columnIndex > getColumnCount()
                || rowIndex < 0 || columnIndex < 0)
            return null;
        return getProperty(datas.get(rowIndex), columnIndex);
    }
}